﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using System.Text;
using Telerik.Sitefinity.Web.UI.ControlDesign;
using Newtonsoft.Json;
using Sitefinity.Contrib.SocialWidgets.Shared;
using System.Collections;

namespace Sitefinity.Contrib.SocialWidgets.Flickr
{
    [ControlDesigner(typeof(FlickrImageRotatorWidgetDesigner)), PropertyEditorTitle("Flickr Image Rotator")]
    public partial class FlickrImageRotatorWidget : System.Web.UI.UserControl
	{
        const string FEED_URL = "http://api.flickr.com/services/feeds/photos_public.gne?id={0}&lang=en-us&format=rss_200";
        const int BUTTON_WIDTH = 24;

        public string UserID { get; set; }
        public int MaximumImages { get; set; }
        public int RotationTimerSeconds { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }

		/// <summary>
		/// Handles the Load event of the Page control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
		protected void Page_Load(object sender, EventArgs e)
		{
            // ensure the username is valid
            if (string.IsNullOrEmpty(UserID)) return;
            
            var sb = new StringBuilder();

            try
            {
                // retrieve contents
                var url = string.Format(FEED_URL, UserID);
                var flickrXml = XDocument.Load(url);
                if (flickrXml == null) return;

                // parse to collection
                XNamespace media = "http://search.yahoo.com/mrss/";
                var photos = from t in flickrXml.Descendants("item") select new { href = t.Element(media + "content").Attribute("url").Value, src = t.Element(media + "content").Attribute("url").Value, alt = t.Element("title").Value };

                // Flickr UserIds include @ signs which break the functionality.
                string prefix = string.Format("flickr_{0}", UserID.Replace("@","_"));
                ImageRotatorUtility imageRotatorUtility = new ImageRotatorUtility(prefix);
                imageRotatorUtility.AddReferences(this.Page);

                string script = imageRotatorUtility.GenerateScript(JsonConvert.SerializeObject(photos), RotationTimerSeconds * 1000);
                Page.ClientScript.RegisterStartupScript(this.GetType(), prefix, script);

                var first = photos.First();
                string html = imageRotatorUtility.GenerateHtml(Width, Height, first.href, first.src, first.alt);
                sb.Append(html);
            }
            catch
            {
                sb.Append("Flickr Image Query failed.");
            }

            
            FlickrImageRotatorHtml.Text = sb.ToString();
		}
	}
}